<template>
  <view>
    <view class="address-wrapper" @click="getAddr">
      <view class="address" v-if="address.userName">
        <view class="receiver">
          <view class="name">收货人：{{ address.userName }}</view>
          <view class="phone-num">{{ address.telNumber }}</view>
          <text class="iconfont icon-arrow-right"></text>
        </view>
        <view class="address-txt"
          >收货地址：{{
            address.provinceName +
              address.cityName +
              address.countyName +
              address.detailInfo
          }}</view
        >
      </view>
      <!-- 选择地址 -->
      <view class="choose-address" v-else>
        <view>请选择地址</view>
        <text class="iconfont icon-arrow-right"></text>
      </view>
      <view class="flower">
        <image src="/static/images/cart_border@2x.png"></image>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-list">
      <view class="goods-item" v-for="(item, index) in goodsList" :key="index">
        <image :src="item.goods_small_logo" alt="" />
        <view class="right">
          <text class="text-line2">{{ item.goods_name }}</text>
          <view class="btm">
            <text class="price"
              >￥<text>{{ item.goods_price }}</text
              >.00</text
            >
            <view class="goods-num">
              <text>{{ item.num }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="bottom-fixed" @click="pay">
      微信支付({{ totalPrice }}.00)
    </view>
  </view>
</template>
<script>
export default {
  data () {
    return {
      // 收货地址对象
      address: wx.getStorageSync('addr') || {},
      // 商品列表
      goodsList: []
    }
  },
  onLoad (options) {
    // 从商详立即购买跳转
    this.goodsId = parseInt(options.goodsId)
    if (this.goodsId) {
      // 构造一个cart
      this.cart = [
        {
          goodsId: this.goodsId,
          checked: true,
          num: 1
        }
      ]
    } else {
      // 取
      this.cart = this.$store.getters.getCart
      // 如果购物车数据是空的,没必要发请求
      if (!this.cart.length) {
        return
      }
      // 只包含选中状态的商品
      this.cart = this.cart.filter(item => {
        return item.checked
      })
    }

    let idsArr = this.cart.map(item => {
      return item.goodsId
    })

    let idsStr = idsArr.join(',')
    this.queryGoodsList(idsStr)
  },
  computed: {
    // 总价
    totalPrice () {
      return this.goodsList.reduce((sum, item) => {
        return sum + item.num * item.goods_price
      }, 0)
    }
    // 收货地址字符串
  },
  methods: {
    consigneeAddr () {
      let address = this.address
      return (
        address.provinceName +
        address.cityName +
        address.countyName +
        address.detailInfo +
        ' ' +
        address.userName +
        ' ' +
        address.telNumber
      )
    },
    // 微信支付
    pay () {
      // 如果没有选择收货地址,提示
      if (!this.address.userName) {
        wx.showToast({
          title: '请选择收货地址',
          icon: 'none'
        })
        return
      }

      // 生成订单
      this.createOrder()
    },
    filterGoodsList () {
      return this.goodsList.map(item => {
        return {
          goods_id: item.goodsId,
          goods_number: item.num,
          goods_price: item.goods_price
        }
      })
    },
    async createOrder () {
      let data = await this.$request({
        url: '/api/public/v1/my/orders/create',
        method: 'POST',
        isAuth: true,
        data: {
          order_price: this.totalPrice,
          consignee_addr: this.consigneeAddr(),
          goods: this.filterGoodsList()
        }
      })

      this.orderNumber = data.order_number
      // 创建订单成功后,删除storage中已勾选的商品
      !this.goodsId && this.arrangeCart()
      this.doPay()
    },
    // 获取支付参数,并唤起微信支付
    async doPay () {
      let data = await this.$request({
        url: '/api/public/v1/my/orders/req_unifiedorder',
        method: 'POST',
        isAuth: true,
        data: {
          order_number: this.orderNumber
        }
      })
      // console.log(data)
      wx.requestPayment({
        ...data.pay,
        success: () => {
          console.log('成功支付')
          wx.navigateTo({
            url: '/pages/order_result/main'
          })
        },
        fail: () => {
          console.log('支付失败')
          wx.navigateTo({
            url: '/pages/order_result/main?orderNumber=' + this.orderNumber
          })
        }
      })
    },
    // 删除storage中已勾选的商品
    arrangeCart () {
      this.$store.commit('arrangeCart')
    },
    async queryGoodsList (idsStr) {
      let goodsList = await this.$request({
        url: '/api/public/v1/goods/goodslist?goods_ids=' + idsStr
      })
      // 遍历cart，取出每一项goodsId，然后，找到后，
      this.goodsList = this.cart.map(item => {
        // 在goodsList找一项商品Id和goodsId相等的那一项
        let targetGoods = goodsList.find(goods => {
          return goods.goods_id === item.goodsId
        })

        // 把那一项和cart元素合并
        return { ...item, ...targetGoods }
      })
    },
    // 获取通讯地址
    getAddr () {
      // 发起授权
      wx.authorize({
        scope: 'scope.address',
        success: () => {
          // 调接口
          wx.chooseAddress({
            success: res => {
              // console.log(res)
              this.address = res
              // 存storage
              wx.setStorageSync('addr', res)
            }
          })
        },
        // 第一次拒绝,拒绝后再点也会进入fail
        fail () {
          // 先提示
          wx.showModal({
            title: '提示',
            content: '请在设置中允许通讯地址',
            success: res => {
              if (res.confirm) {
                // 打开设置
                wx.openSetting({})
              }
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="less">
.address-wrapper {
  background-color: #fff;
}

.address {
  display: flex;
  flex-direction: column;
  padding: 44rpx 30rpx 48rpx 20rpx;

  .receiver {
    display: flex;
    justify-content: space-between;
    margin-bottom: 50rpx;
    position: relative;

    .phone-num {
      margin-right: 40rpx;
    }

    .icon-arrow-right {
      position: absolute;
      top: 8rpx;
      right: 0;
      color: #999;
    }
  }
}

.choose-address {
  display: flex;
  padding: 44rpx 30rpx 48rpx 20rpx;
  justify-content: space-between;

  .icon-arrow-right {
    color: #999;
  }
}

.flower {
  image {
    height: 16rpx;
    width: 100%;
    display: block;
  }
}

.goods-item {
  height: 206rpx;
  background-color: #fff;
  border-top: 1rpx solid #ddd;
  display: flex;
  box-sizing: border-box;
  align-items: center;

  image {
    width: 160rpx;
    height: 160rpx;
    margin-left: 30rpx;
  }

  .right {
    flex: 1;
    display: flex;
    flex-direction: column;
    margin: 0 20rpx 0 18rpx;

    .btm {
      display: flex;
      margin-top: 40rpx;
      justify-content: space-between;

      .price {
        color: #eb4450;

        > text {
          font-size: 24px;
        }
      }

      .goods-num {
        display: flex;
        align-items: center;

        button {
          width: 60rpx;
          height: 50rpx;
          box-sizing: border-box;
          display: flex;
          justify-content: center;
          align-items: center;
          border: 4rpx solid #666;
        }

        text {
          margin: 0 30rpx;
        }
      }
    }
  }
}

.goods-list {
  position: absolute;
  bottom: 98rpx;
  top: 243rpx;
  width: 100%;
  overflow: auto;
  padding-bottom: 60rpx;
  background-color: #f4f4f4;
}

.bottom-fixed {
  position: absolute;
  height: 98rpx;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #1aad19;
  color: #fff;
  line-height: 98rpx;
  text-align: center;
}
</style>
